import React, { memo, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { TableContentStyle } from './style';
import { Pagination, Table } from 'antd';
import { useMergeRenders, useScrollHeight } from '../utils';
import { useRemoveCustomProps } from '@/hooks/useRemoveCustomProps';
import { ReloadOutlined } from '@ant-design/icons';
import { useDataContext } from '../context';
import './style.css';
import type { PaginationProps } from 'antd';
import type { AnyObject, MainTableProps, TableProRef } from '../type';

// 记录扩展的属性，用于删除不属于<Table />的props属性
const extendProps = ['tableName', 'tableHeight', 'padding', 'toolbar', 'renders', 'index'];

const TableContent = memo(<RecordType extends AnyObject>(props: MainTableProps<RecordType>) => {
	const {
		tableName,
		toolbar,
		// tableHeight,
		scrollHeight: scrollContentHeight,
		// toolbarPadding = true,
		tableRef: tableProRef,
		request,
		onPageChange
	} = props;
	const { payload, tableHeight, tableListRef, setPageInfoAction } = useDataContext();

	const [tableLoading, setTableLoading] = useState(false);
	const [tableData, setTableData] = useState<{
		list: Awaited<ReturnType<typeof request>>['list'];
		total: number;
	}>({ list: [], total: 0 });
	const { tableRef, pageRef, showScroll, scrollHeight, showScrollFn } = useScrollHeight(
		props,
		tableData,
		tableHeight,
		scrollContentHeight
	);

	// 查询列表数据
	const queryList = async (pageNo: number, pageSize: number) => {
		setTableLoading(true);
		// setPageInfoAction(1, payload.pageSize);
		const { list = [], total } = await request({ pageNo, pageSize }, payload.param).finally(() =>
			setTableLoading(false)
		);
		setPageInfoAction(pageNo, pageSize);
		setTableData(() => {
			if (total === undefined) {
				tableListRef.current.list = list;
				tableListRef.current.hasTotal = false;
				const { pageNo, pageSize } = payload;
				const start = (pageNo - 1) * pageSize;
				return {
					list: list.slice(start, start + pageSize),
					total: list.length
				};
			} else {
				return { list: list, total: total };
			}
		});
	};
	useEffect(() => {
		if (!tableListRef.current.isPageChange) {
			if (tableListRef.current.list.length) tableListRef.current.list = [];
			queryList(payload.pageNo, payload.pageSize);
		}
	}, [payload.param]);

	// 刷修方法
	const refreshFn = () => {
		if (request?.[Symbol.toStringTag] === 'AsyncFunction') {
			tableListRef.current.isPageChange = false;
			queryList(payload.pageNo, payload.pageSize);
		}
	};

	// 合并自定义render后的columns
	const newColumns = useMergeRenders(props, {
		pageNo: payload.pageNo,
		pageSize: payload.pageSize
	});

	// 删除不属于<Table />的props属性
	const TableProps = useRemoveCustomProps<MainTableProps>(props, extendProps);

	const pageInfo = useMemo<false | PaginationProps>(() => {
		if (!TableProps.pagination && TableProps.pagination !== false) {
			return {
				current: payload.pageNo,
				pageSize: payload.pageSize,
				total: tableData.total,
				onChange: (pageNo, pageSize) => {
					if (tableListRef.current.hasTotal) {
						queryList(pageNo, pageSize);
					} else {
						const start = (pageNo - 1) * pageSize;
						setTableData((prev) => ({
							...prev,
							list: tableListRef.current.list.slice(start, start + pageSize)
						}));
						setPageInfoAction(pageNo, pageSize);
						onPageChange?.(pageNo, pageSize);
					}
				}
			};
		} else {
			return TableProps.pagination;
		}
	}, [tableData]);

	useImperativeHandle<any, TableProRef>(tableProRef, () => ({ reload: refreshFn }));

	return (
		<TableContentStyle
			// toolbar_padding={toolbarPadding}
			content_height={tableHeight}
			table_size={TableProps.size}
		>
			<div className="toolbars">
				<div>
					<span className="title">{tableName}</span>
					<ReloadOutlined className="refresh" onClick={refreshFn} />
				</div>
				{toolbar && <div className="tools_btns">{toolbar}</div>}
			</div>
			<Table
				ref={tableRef}
				loading={tableLoading}
				rowKey="id"
				bordered
				scroll={showScroll ? { y: scrollHeight, x: 'max-content' } : { x: 'max-content' }}
				{...TableProps}
				columns={newColumns}
				dataSource={props.pagination ? TableProps.dataSource : tableData.list}
				pagination={false}
				expandable={{
					onExpandedRowsChange: () => {
						setTimeout(() => {
							showScrollFn();
						}, 0);
					}
				}}
			/>
			{TableProps.pagination !== false && (
				<div
					className="pagination"
					ref={pageRef}
					style={{ position: scrollContentHeight ? 'static' : 'absolute' }}
				>
					<Pagination
						showQuickJumper
						showSizeChanger
						pageSizeOptions={[10, 50, 100, 200]}
						showTotal={(total) => `共 ${total} 条`}
						size={TableProps.size === 'small' ? 'small' : 'default'}
						{...pageInfo}
					/>
				</div>
			)}
		</TableContentStyle>
	);
}) as <T>(props: MainTableProps<T>) => React.ReactElement;

export default TableContent;
